from flask import Blueprint,render_template,redirect,request,url_for,flash
from exts import db
from model.models import DishType
from fromVal import dishTypeForm

bp = Blueprint('dish_type',__name__,url_prefix='/dishtype')


@bp.route("/")
def index():
    # 查询所有菜品
    dish_types = DishType.query.all()
    return render_template('dish_type/dish_type_index.html', dish_types=dish_types)


# 新增菜品
@bp.route("/add",methods=['POST','GET'])
def add_dish_type():
    if request.method == 'GET':
        return render_template("dish_type/add_dish_type.html")
    elif request.method == 'POST':
        form = dishTypeForm.addDishTypeForm(request.form)
        # 表单验证通过
        if form.validate():
            dish_type_name = form.dish_type_name.data
            dish_type = DishType(dish_type_name=dish_type_name)
            # 保存到数据库
            db.session.add(dish_type)
            db.session.commit()
            return redirect(url_for('dish_type.index'))
        else:
            for errors in form.errors.values():
                for error in errors:
                    flash(error)
            return redirect(url_for('dish_type.add_dish_type'))


@bp.route("/update",methods=['POST','GET'])
def update_dish_type():
    if request.method == 'GET':
        dish_types = DishType.query.filter(DishType.is_delete==0)
        return render_template("dish_type/update_dish_type.html",dish_types=dish_types)
    elif request.method == 'POST':
        form = dishTypeForm.UpdateDishType(request.form)
        if form.validate():
            old_dish_type_name = form.old_dish_type_name.data
            dish_type_name = form.dish_type_name.data
            # 修改数据
            dish_type = DishType.query.filter(DishType.dish_type_name==old_dish_type_name).first()
            dish_type.dish_type_name = dish_type_name
            db.session.commit()
            print(old_dish_type_name)
            print(dish_type_name)
            return redirect(url_for('dish_type.update_dish_type'))
        else:
            for errors in form.errors.values():
                for error in errors:
                    flash(error)
            return redirect(url_for('dish_type.update_dish_type'))


@bp.route("/delete")
def delete_dish_type():
    dish_type_no = request.args.get('dish_type_no')
    dish_type = DishType.query.filter(DishType.dish_type_no==dish_type_no).first()
    dish_type.is_delete = 1
    db.session.commit()
    print(dish_type_no)
    return redirect(url_for('dish_type.index'))


@bp.route("/wakeup")
def wakeup():
    dish_type_no = request.args.get('dish_type_no')
    dish_type = DishType.query.filter(DishType.dish_type_no==dish_type_no).first()
    dish_type.is_delete = 0
    db.session.commit()
    print(dish_type_no)
    return redirect(url_for('dish_type.index'))